#include "dialogaddfood.h"
#include "ui_dialogaddfood.h"
#include <QAbstractItemView>
#include <QDebug>
#include <QSqlError>

DialogAddFood::DialogAddFood(DialogMealDataManage *mealManageDialog, QSqlDatabase *db, QWidget *parent) :
    QDialog(parent, Qt::Window),
    ui(new Ui::DialogAddFood),
    m_db(db),
    m_mealManageDialog(mealManageDialog)
{
    ui->setupUi(this);
    m_foodType = -1;
    ui->comboBoxFoodType->initialize(db);

    m_model = new QSqlQueryModel(this);
    m_queryBase = "SELECT rowId, foodName, foodCalorie, foodProtein, foodCh, foodFat, foodCost, foodUnit FROM foods";
    m_model->setQuery(m_queryBase, *db);
    m_model->setHeaderData(0, Qt::Horizontal, "ID");
    m_model->setHeaderData(1, Qt::Horizontal, "Név");
    m_model->setHeaderData(2, Qt::Horizontal, "Energia");
    m_model->setHeaderData(3, Qt::Horizontal, "Fehérje");
    m_model->setHeaderData(4, Qt::Horizontal, "Szénhidrát");
    m_model->setHeaderData(5, Qt::Horizontal, "Zsír");
    m_model->setHeaderData(6, Qt::Horizontal, "Költség");
    m_model->setHeaderData(7, Qt::Horizontal, "Egység");
    ui->tableViewFoods->setModel(m_model);

    ui->tableViewFoods->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableViewFoods->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
    ui->tableViewFoods->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);

    ui->tableViewFoods->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewFoods->setSelectionMode(QAbstractItemView::SingleSelection);
}

DialogAddFood::~DialogAddFood()
{
    delete ui;
}

void DialogAddFood::showEvent(QShowEvent *event)
{
    ui->pushButtonAdd->setFocus();
    QDialog::showEvent(event);
}

void DialogAddFood::updateFilter()
{
    m_nameFilter = ui->lineEditSearch->text();
    m_foodType = ui->comboBoxFoodType->itemData(ui->comboBoxFoodType->currentIndex()).toInt();

    bool andNeed = false;
    QString query = m_queryBase;

    if (m_foodType != -1) {
        query.append(QString(" WHERE foodType == %1").arg(m_foodType));
        andNeed = true;
    }

    if (m_nameFilter != "") {
        if (andNeed) {
            query.append(" AND ");
        } else {
            query.append(" WHERE ");
        }

        query.append(" foodName LIKE '%"+m_nameFilter+"%'");
    }
    m_model->setQuery(query, *m_db);

}

void DialogAddFood::on_pushButtonAdd_clicked()
{
    QSqlQuery *addQuery;
    if (ui->tableViewFoods->selectionModel()->selectedRows(0).size()) {
        addQuery = new QSqlQuery(*m_db);
        addQuery->prepare("INSERT INTO meals (mealDate, mealType, foodId, foodAmount) "
                          "VALUES (:date, :mealType, :foodId, :amount)");
        addQuery->bindValue(":date", m_date);
        addQuery->bindValue(":mealType", m_type);
        addQuery->bindValue(":foodId", m_model->data(ui->tableViewFoods->selectionModel()->selectedRows(0).first()));
        addQuery->bindValue(":amount", ui->doubleSpinBoxAmount->value());
        if(addQuery->exec()) {
            emit mealAdded();
            this->close();
        } else {
            qWarning() << addQuery->lastError().databaseText() << addQuery->lastQuery();
        }
    }
}

void DialogAddFood::on_comboBoxFoodType_activated(int )
{
    updateFilter();
}

void DialogAddFood::setType(MealModel::MealType type)
{
    m_type = type;
    switch (type) {
    case MealModel::MealType_BreakFast:
        this->setWindowTitle("Hozzáadás a reggelihez");
        break;
    case MealModel::MealType_Lunch:
        this->setWindowTitle("Hozzáadás az ebédhez");
        break;
    case MealModel::MealType_Dinner:
        this->setWindowTitle("Hozzáadás a vacsorához");
        break;
    }
}

void DialogAddFood::on_lineEditSearch_textChanged(const QString &)
{
    updateFilter();
}

void DialogAddFood::on_tableViewFoods_clicked(const QModelIndex &index)
{
    QModelIndex indexAmount = m_model->index(index.row(), 7);
    ui->doubleSpinBoxAmount->setSuffix(QString(" x %1").arg(m_model->data(indexAmount).toString()));
}

void DialogAddFood::on_pushButtonEdit_clicked()
{
    QModelIndex index = ui->tableViewFoods->currentIndex();
    m_mealManageDialog->showMealData(m_model->data(m_model->index(index.row(), 0)).toInt());
    m_mealManageDialog->show();
}
